/*
 * libustream: User-space stackable streams - Utilities
 * @(#) $Id: uscat.c 2 2009-02-20 09:52:11Z mo@ilaven.net $
 */

/*
 * Copyright (c) 2002, 2008 Mo McRoberts.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The names of the author(s) of this software may not be used to endorse
 *    or promote products derived from this software without specific prior
 *    written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL
 * AUTHORS OF THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include <stdio.h>
#include <errno.h>

#include "ustream/ustream.h"

const char *progname = "cat";

static char buffer[128];

int
do_cat(const char *src)
{
	IUStream *stream;
	ssize_t l;
	int r;
	
	r = 0;
	if(0 == strcmp(src, "-"))
	{
		src = "fd:///stdin";
	}
	if(NULL == (stream = us_create(src, O_RDONLY, 0)))
	{
		fprintf(stderr, "%s: %s: %s\n", progname, src, strerror(errno));
		return 1;
	}
	while(0 != (l = us_get(stream, buffer, sizeof(buffer))))
	{
		if(-1 == l)
		{
			if(EPIPE != errno)
			{
				fprintf(stderr, "%s: %s: %s\n", progname, src, strerror(errno));
				r = 1;
			}
			break;
		}
		fwrite(buffer, l, 1, stdout);
	}
	us_destroy(stream);
	return r;
}

int
main(int argc, char **argv)
{
	int r, c;
	
	progname = argv[0];
	r = 0;
	if(argc == 1)
	{
		return 0 == do_cat("-") ? 0 : 1;
	}
	for(c = 1; c < argc; c++)
	{
		if(0 != do_cat(argv[c]))
		{
			r = 1;
		}
	}
	return r;
}